// @ts-check

/**
 * @typedef {{
 *  id: number
 *  goodsId: string
 *  scaleDesc: string
 *  scaleUnit: string
 *  scalePeriod: number
 * }} GoodsInfo
 * @typedef {{
 *  id: number
 *  goodsId: string
 *  productName: string
 *  unitPrice: number
 *  unit: string
 *  unitScale: number
 *  coefficient: number
 * }} GoodsProduct
 * @typedef {{
 *  id: number
 *  goodsId: string
 *  productId: string
 *  chainName: string
 *  indexName: string
 *  unitPrice?: number
 *  unitCategory?: string
 *  coefficient: number
 *  order: number
 *  isFixedInvest: number
 * }} GoodsStore
 */

import { IDB } from '@vimi/utils-tool'

const localInfo = {
  '0b19cbc5-1200-420a-bc92-91e51b1629ba': {
    scaleDesc: '育肥猪',
    scaleUnit: '头',
    scalePeriod: 5,
  },
  '85051255-f124-4927-884f-3226ca7fdef7': {
    scaleDesc: '种植规模',
    scaleUnit: '亩',
    scalePeriod: 10,
  },
  '99bec347-7d53-40e8-9679-e0b4c5a00a1e': {
    scaleDesc: '房间数',
    scaleUnit: '间',
    scalePeriod: 5,
  },
}

const localProduct = {
  '0b19cbc5-1200-420a-bc92-91e51b1629ba': [
    {
      id: 1,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
      productName: '育肥猪',
      unitPrice: 30,
      unit: '元/斤',
      unitScale: 200,
      coefficient: 0.5,
    },
  ],
  '85051255-f124-4927-884f-3226ca7fdef7': [
    {
      id: 2,
      productName: '茶油',
      unitPrice: 140,
      unit: '元/公斤',
      unitScale: 40,
      coefficient: 0.5,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
    },
    {
      id: 3,
      productName: '茶籽',
      unitPrice: 17,
      unit: '元/公斤',
      unitScale: 140,
      coefficient: 0.5,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      indexes: [],
    },
    {
      id: 4,
      productName: '鲜果',
      unitPrice: 4,
      unit: '元/公斤',
      unitScale: 550,
      coefficient: 0.5,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      indexes: [],
    },
  ],
  '99bec347-7d53-40e8-9679-e0b4c5a00a1e': [
    {
      id: 1,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productName: '标准间',
      unitPrice: 200,
      unit: '元/间',
      unitScale: 255,
      coefficient: 0.6,
    },
  ],
}

const localStore = {
  '0b19cbc5-1200-420a-bc92-91e51b1629ba': [
    {
      chainName: '基建',
      productId: 1,
      indexName: '猪栏建设',
      unitPrice: 110,
      coefficient: 0.9,
      order: 0,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
      isFixedInvest: 1,
    },
    {
      chainName: '基建',
      productId: 1,
      indexName: '设施',
      unitPrice: 55,
      coefficient: 0.9,
      order: 1,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
      isFixedInvest: 1,
    },
    {
      chainName: '基建',
      productId: 1,
      indexName: '猪粪处理设施',
      unitPrice: 36,
      coefficient: 0.9,
      order: 2,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
      isFixedInvest: 1,
    },
    {
      chainName: '基建',
      productId: 1,
      indexName: '固定资产折旧',
      unitPrice: 67,
      coefficient: 0.8,
      order: 3,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '基建',
      productId: 1,
      indexName: '利息+担保费',
      unitPrice: 20,
      coefficient: 0.8,
      order: 4,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '母猪饲养',
      unitPrice: 170,
      coefficient: 0.7,
      order: 5,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '猪仔饲养',
      unitPrice: 400,
      coefficient: 0.7,
      order: 6,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '饲料',
      unitPrice: 714,
      coefficient: 0.7,
      order: 8,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '人工',
      unitPrice: 480,
      coefficient: 0.7,
      order: 7,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '维护费',
      unitPrice: 10,
      coefficient: 0.7,
      order: 9,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '疫苗保健',
      unitPrice: 100,
      coefficient: 0.7,
      order: 10,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '水电费',
      unitPrice: 50,
      coefficient: 0.7,
      order: 11,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
    {
      chainName: '养殖',
      productId: 1,
      indexName: '其他',
      unitPrice: 10,
      coefficient: 0.7,
      order: 12,
      goodsId: '0b19cbc5-1200-420a-bc92-91e51b1629ba',
    },
  ],
  '85051255-f124-4927-884f-3226ca7fdef7': [
    {
      indexName: '油茶种植用地',
      chainName: '地租',
      unitPrice: 200,
      coefficient: 1,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 0,
      isFixedInvest: 1,
    },
    {
      indexName: '清除山上杂草，对垮塌的破坎进行修护',
      chainName: '清山整地',
      unitPrice: 100,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 1,
      isFixedInvest: 1,
    },
    {
      indexName: '挖70cm*70cm*70cm的大穴',
      chainName: '挖穴',
      unitPrice: 110,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 2,
      isFixedInvest: 1,
    },
    {
      indexName: '穴施有机肥1kg左右',
      chainName: '基肥',
      unitPrice: 220,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 3,
    },
    {
      indexName: '每亩种植110株，以成活率80%计',
      chainName: '种苗',
      unitPrice: 50,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 4,
    },
    {
      indexName: '表土混肥回填，苗木运输，定植',
      chainName: '栽苗',
      unitPrice: 20,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 5,
    },
    {
      indexName: '包括除草，打药，施肥，修建等',
      chainName: '幼苗管理',
      unitPrice: 40,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 6,
    },
    {
      indexName: '疏松土壤，每年至少2次',
      chainName: '浅耕除草',
      unitPrice: 150,
      coefficient: 0.9,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 7,
    },
    {
      indexName: '治病杀虫类',
      chainName: '农药',
      unitPrice: 15,
      coefficient: 0.8,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 8,
    },
    {
      indexName: '化学除草剂',
      chainName: '除草',
      unitPrice: 20,
      coefficient: 0.8,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 9,
    },
    {
      indexName: '春夏季节施速效肥提苗',
      chainName: '施肥',
      unitPrice: 55,
      coefficient: 0.8,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 2,
      order: 10,
    },
    {
      indexName: '采摘',
      chainName: '人工',
      unitPrice: 100,
      coefficient: 0.8,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 3,
      order: 1,
    },
    {
      indexName: '采摘',
      chainName: '人工',
      unitPrice: 100,
      coefficient: 0.8,
      goodsId: '85051255-f124-4927-884f-3226ca7fdef7',
      productId: 4,
      order: 1,
    },
  ],
  '99bec347-7d53-40e8-9679-e0b4c5a00a1e': [
    {
      indexName: '宅基地改造',
      chainName: '基建',
      unitPrice: 5000,
      coefficient: 0.8,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 0,
      id: 1,
      isFixedInvest: 1,
    },
    {
      indexName: '房屋设计',
      chainName: '基建',
      unitPrice: 1000,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 1,
      isFixedInvest: 1,
      id: 2,
    },
    {
      indexName: '装饰',
      chainName: '基建',
      unitPrice: 200,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 2,
      isFixedInvest: 1,
      id: 3,
    },
    {
      indexName: '数字化',
      chainName: '基建',
      unitPrice: 200,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 3,
      isFixedInvest: 1,
      id: 4,
    },
    {
      indexName: '绿化',
      chainName: '基建',
      unitPrice: 500,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 4,
      isFixedInvest: 1,
      id: 5,
    },
    {
      indexName: '水电',
      chainName: '基建',
      unitPrice: 200,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 5,
      isFixedInvest: 1,
      id: 6,
    },
    {
      indexName: '餐饮',
      chainName: '基建',
      unitPrice: 100,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 6,
      isFixedInvest: 1,
      id: 7,
    },
    {
      indexName: '娱乐',
      chainName: '管理',
      unitPrice: 100,
      coefficient: 0.7,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 7,
      isFixedInvest: 1,
      id: 8,
    },
    {
      indexName: '人工',
      chainName: '管理',
      unitPrice: 300,
      coefficient: 0.6,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 8,
      isFixedInvest: 0,
      id: 9,
    },
    {
      indexName: '维护',
      chainName: '管理',
      unitPrice: 100,
      coefficient: 0.6,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 9,
      isFixedInvest: 0,
      id: 10,
    },
    {
      indexName: '日常经营',
      chainName: '管理',
      unitPrice: 50,
      coefficient: 0.6,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 10,
      isFixedInvest: 0,
      id: 11,
    },
    {
      indexName: '营销',
      chainName: '管理',
      unitPrice: 50,
      coefficient: 0.6,
      goodsId: '99bec347-7d53-40e8-9679-e0b4c5a00a1e',
      productId: 1,
      order: 11,
      isFixedInvest: 0,
      id: 12,
    },
  ],
}

const dbName = 'goods'
const dbVersion = 1

const infoTableName = 'info'
const productTableName = 'product'
const storeTableName = 'store'
const tables = [
  {
    tableName: infoTableName,
    options: { keyPath: 'id', autoIncrement: true },
    indexes: [{ key: 'id', option: { unique: true } }, { key: 'goodsId' }],
  },
  {
    tableName: productTableName,
    options: { keyPath: 'id', autoIncrement: true },
    indexes: [{ key: 'id', option: { unique: true } }, { key: 'goodsId' }],
  },
  {
    tableName: storeTableName,
    options: { keyPath: 'id', autoIncrement: true },
    indexes: [{ key: 'id', option: { unique: true } }, { key: 'goodsId' }],
  },
]

/** @type {IDB} */
let idb

const getIdb = async () => {
  if (!idb) {
    idb = await IDB.init({
      dbName,
      version: dbVersion,
      tables,
    })
  }
  return idb
}

/**
 * 获取产品所有指标
 * @param {string} goodsId 产品ID
 * @returns {Promise<GoodsStore[]>}
 */
export const getStoreByGoodsId = goodsId =>
  getIdb()
    .then(db => {
      return db.query({ tableName: storeTableName, condition: data => data.goodsId === goodsId })
    })
    .then(res => (res && res.length ? res : localStore[goodsId] || []))

/**
 * 更改数据
 * @param {string} id id
 * @param {Partial<GoodsStore>} data 更改后的数据
 * @returns {Promise<GoodsStore>}
 */
export const updateStore = (id, data) =>
  getIdb().then(db => {
    return db.updateByPrimaryKey({
      tableName: storeTableName,
      value: id,
      handler: d => ({
        ...d,
        ...data,
      }),
    })
  })

/**
 * 删除数据
 * @param {string} id id
 */
export const deleteStore = id =>
  getIdb().then(db => {
    return db.deleteByPrimaryKey({ tableName: storeTableName, value: id })
  })

/**
 * 添加数据
 * @param {Exclude<GoodsStore, 'id'>} data 添加的数据
 */
export const addStore = data =>
  getIdb().then(db => {
    return db.insert({ tableName: storeTableName, data })
  })

/**
 * 批量更改（增删改）数据
 * @param {string} goodsId 产品ID
 * @param {Partial<GoodsStore>[]} data 最终数据
 */
export const addStores = (goodsId, data) =>
  getIdb()
    .then(async db => {
      const store = db.db.transaction(storeTableName, 'readwrite').objectStore(storeTableName)
      await db.cursorHandler(
        store,
        d => d.goodsId === goodsId,
        cursor => cursor.delete()
      )
      return store
    })
    .then(store => {
      data.forEach(v => store.add({ ...v, goodsId }))
      return data.length
    })

/**
 * 获取产品基本信息
 * @param {string} goodsId 产品ID
 * @returns {Promise<GoodsInfo>}
 */
export const getInfo = goodsId =>
  getIdb()
    .then(async db => {
      return db.query({ tableName: infoTableName, condition: data => data.goodsId === goodsId })
    })
    .then(res => (res && res.length ? res[0] : localInfo[goodsId]))

/**
 * 添加或修改基本信息
 * @param {string} goodsId 产品ID
 * @param {Partial<GoodsInfo>} data 基本信息
 */
export const putInfo = (goodsId, data) =>
  getIdb().then(async db => {
    const store = db.db.transaction(infoTableName, 'readwrite').objectStore(infoTableName)
    const info = await db.cursorHandler(store, d => d.goodsId === goodsId)
    if (info && info.length) {
      data.id = info[0].id
    }
    data.goodsId = goodsId
    store.put(data)
  })

/**
 * 获取产品列表
 * @param {string} goodsId 产品ID
 * @returns {Promise<GoodsProduct[]>}
 */
export const getProduct = goodsId =>
  getIdb()
    .then(async db => {
      return db.query({ tableName: productTableName, condition: data => data.goodsId === goodsId })
    })
    .then(res => (res && res.length ? res : localProduct[goodsId] || []))

/**
 * 添加产品
 * @param {Partial<GoodsProduct>} data 产品信息
 */
export const addProduct = data =>
  getIdb().then(async db => {
    return db.insert({ tableName: productTableName, data: data })
  })

/**
 * 修改产品
 * @param {string} id 产品ID
 * @param {Partial<GoodsProduct>} data 产品信息
 */
export const updateProduct = (id, data) =>
  getIdb().then(async db => {
    return db.updateByPrimaryKey({
      tableName: productTableName,
      value: id,
      handler: d => ({
        ...d,
        ...data,
      }),
    })
  })

/**
 * 删除产品
 * @param {string} id id
 */
export const deleteProduct = id =>
  getIdb().then(db => {
    return db.deleteByPrimaryKey({ tableName: productTableName, value: id })
  })
